package com.example.elderlycare.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elderlycare.controller.entity.ElderRequestBody;
import com.example.elderlycare.dao.entity.Elder;
import com.example.elderlycare.service.ElderService;
import com.example.elderlycare.service.entity.ElderListResponseBody;
import com.example.elderlycare.utils.Result;
import com.example.elderlycare.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/elder")
@Slf4j
public class ElderController {
    @Resource
    ElderService elderService;

    /**
     * 根据参数查询老人信息的接口
     *
     * @param id       老人 id
     * @param name     老人名字
     * @param sex      老人性别 0--男，1--女
     * @param relative 亲属姓名
     * @param pageSize 页大小
     * @param current  当前页
     * @return ElderListResponseBody
     */
    @GetMapping("/query")
    public Result<ElderListResponseBody> queryElders(
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "sex", required = false) String sex,
            @RequestParam(value = "elderNumber", required = false) String elderNumber,
            @RequestParam(value = "certificateId", required = false) String certificateId,
            @RequestParam(value = "relative", required = false) String relative,
            @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
            @RequestParam(defaultValue = "1", value = "current") int current
    ) {
        Map<String, Object> params = new HashMap<>();

        params.put("id", id);
        params.put("limit", pageSize);
        params.put("offset", (current - 1) * pageSize);
        params.put("name", name != null ? "%" + name + "%" : null);
        params.put("relative", relative != null ? "%" + relative + "%" : null);
        params.put("sex", sex);
        params.put("elderNumber", elderNumber);
        params.put("certificateId", certificateId);

        try {
            ElderListResponseBody res = elderService.queryElders(params);
            return Result.success(res);
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }


    /**
     * 添加老人信息的接口
     *
     * @param req ElderRequestBody.addElder
     * @return Elder
     */
    @PostMapping("/add")
    public Result<?> addElder(@RequestBody ElderRequestBody.addElder req) {
        Elder elder = Elder.builder()
                .name(req.getName())
                .phone(req.getPhone())
                .number(req.getNumber())
                .sex(req.getSex())
                .birthday(req.getBirthday())
                .certificateId(req.getCertificateId())
                .build();
        QueryWrapper<Elder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("certificate_id", elder.getCertificateId()).eq("number", elder.getNumber());
        Elder exitElder = elderService.getOne(queryWrapper);
        if (exitElder != null) {
            log.warn("add elder error, this elder already exists.");
            Integer elderId = exitElder.getId();
            Map<String, Object> params = new HashMap<>();
            params.put("id", elderId);
            ElderListResponseBody res = elderService.queryElders(params);
            return Result.error(ResultEnum.ELDER_EXISTED_ERROR, res.getElderItemList().get(0));
        }
        try {
            boolean save = elderService.save(elder);
            if (save) {
                Elder elderRecord = elderService.getOne(queryWrapper);
                return Result.success(elderRecord);
            } else {
                log.warn("add elder error.");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 删除老人信息的接口
     *
     * @param id 老人的信息的id
     * @return null
     */
    @DeleteMapping("/delete")
    public Result<?> deleteElder(@RequestParam("id") @NotEmpty Integer id) {
        try {
            boolean flag = elderService.removeById(id);
            if (flag) {
                return Result.success(null);
            } else {
                log.warn("delete elder error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 修改老人信息的接口
     *
     * @param req ElderRequestBody.updateElder
     * @return null
     */
    @PutMapping("/update")
    public Result<?> updateElder(@RequestBody ElderRequestBody.updateElder req) {
        Elder elder = Elder.builder()
                .id(req.getId())
                .name(req.getName())
                .phone(req.getPhone())
                .number(req.getNumber())
                .sex(req.getSex())
                .birthday(req.getBirthday())
                .certificateId(req.getCertificateId())
                .build();
        try {
            boolean flag = elderService.updateById(elder);
            if (flag) {
                return Result.success(null);
            } else {
                log.warn("update elder error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }
}
